#include <QPainter>
#include <QTimer>
#include <QSoundEffect>
#include <QMouseEvent>
#include <QMessageBox>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QDebug>
#include <math.h>
#include <QUrl>
#include "mainwindow.h"

// 全局音效对象定义
QSoundEffect placeStoneSound;  // 落子音效
QSoundEffect defeatSound;      // 失败音效
QSoundEffect victorySound;     // 胜利音效

// 游戏界面常量定义
const int BOARD_EDGE_SPACE = 30;    // 棋盘边缘留白
const int STONE_RADIUS = 15;        // 棋子半径
const int MOVE_MARKER_SIZE = 6;     // 落子标记大小
const int GRID_SIZE = 40;           // 每个格子的大小
const int CLICK_TOLERANCE = 20;     // 鼠标点击容差范围
const int AI_THINKING_DELAY = 700;  // AI思考延迟(毫秒)

// 构造函数：初始化主窗口
GomokuMainWindow::GomokuMainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    // 设置音效文件路径
    placeStoneSound.setSource(QUrl::fromLocalFile(":/res/sound/chessone.wav"));
    defeatSound.setSource(QUrl::fromLocalFile(":/res/sound/lose.wav"));
    victorySound.setSource(QUrl::fromLocalFile(":/res/sound/win.wav"));

    // 设置固定窗口大小（根据棋盘尺寸计算）
    setFixedSize(BOARD_EDGE_SPACE * 2 + GRID_SIZE * BOARD_DIMENSION,
                 BOARD_EDGE_SPACE * 2 + GRID_SIZE * BOARD_DIMENSION);

    // 启用鼠标跟踪
    setMouseTracking(true);

    // 创建游戏菜单
    QMenu *gameMenu = menuBar()->addMenu(tr("Game"));

    // 添加"人对人"游戏选项
    QAction *actionPVP = new QAction("Person VS Person", this);
    connect(actionPVP, SIGNAL(triggered()), this, SLOT(startPvPGame()));
    gameMenu->addAction(actionPVP);

    // 添加"人对AI"游戏选项
    QAction *actionPVE = new QAction("Person VS Computer", this);
    connect(actionPVE, SIGNAL(triggered()), this, SLOT(startPvEGame()));
    gameMenu->addAction(actionPVE);

    // 初始化新游戏
    setupNewGame();
}

// 析构函数：清理资源
GomokuMainWindow::~GomokuMainWindow()
{
    if (gameEngine)
    {
        delete gameEngine;  // 释放游戏引擎
        gameEngine = nullptr;
    }
}

// 初始化新游戏
void GomokuMainWindow::setupNewGame()
{
    gameEngine = new GomokuGameEngine;  // 创建游戏引擎实例
    startPvPGame();                    // 默认启动人对人模式
}

// 启动人对人游戏
void GomokuMainWindow::startPvPGame()
{
    currentGameMode = HUMAN_VS_HUMAN;      // 设置游戏模式
    gameEngine->currentState = GAME_ACTIVE; // 设置游戏状态为进行中
    gameEngine->initializeGame(currentGameMode); // 初始化游戏
    update();                              // 更新界面
}

// 启动人对AI游戏
void GomokuMainWindow::startPvEGame()
{
    currentGameMode = HUMAN_VS_AI;         // 设置游戏模式
    gameEngine->currentState = GAME_ACTIVE; // 设置游戏状态为进行中
    gameEngine->initializeGame(currentGameMode); // 初始化游戏
    update();                              // 更新界面
}

// 绘制事件：绘制整个游戏界面
void GomokuMainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true); // 开启抗锯齿

    // 绘制棋盘网格线
    for (int i = 0; i < BOARD_DIMENSION + 1; i++)
    {
        // 绘制垂直线
        painter.drawLine(BOARD_EDGE_SPACE + GRID_SIZE * i, BOARD_EDGE_SPACE,
                         BOARD_EDGE_SPACE + GRID_SIZE * i, size().height() - BOARD_EDGE_SPACE);
        // 绘制水平线
        painter.drawLine(BOARD_EDGE_SPACE, BOARD_EDGE_SPACE + GRID_SIZE * i,
                         size().width() - BOARD_EDGE_SPACE, BOARD_EDGE_SPACE + GRID_SIZE * i);
    }

    QBrush brush;
    brush.setStyle(Qt::SolidPattern); // 设置画刷样式

    // 绘制落子位置提示标记
    if (hoverRow > 0 && hoverRow < BOARD_DIMENSION &&
        hoverCol > 0 && hoverCol < BOARD_DIMENSION &&
        gameEngine->boardState[hoverRow][hoverCol] == 0)
    {
        // 根据当前玩家设置标记颜色
        if (gameEngine->isPlayerTurn)
            brush.setColor(Qt::white);
        else
            brush.setColor(Qt::black);
        painter.setBrush(brush);
        // 绘制标记矩形
        painter.drawRect(BOARD_EDGE_SPACE + GRID_SIZE * hoverCol - MOVE_MARKER_SIZE / 2,
                         BOARD_EDGE_SPACE + GRID_SIZE * hoverRow - MOVE_MARKER_SIZE / 2,
                         MOVE_MARKER_SIZE, MOVE_MARKER_SIZE);
    }

    // 绘制所有棋子
    for (int i = 0; i < BOARD_DIMENSION; i++)
    {
        for (int j = 0; j < BOARD_DIMENSION; j++)
        {
            if (gameEngine->boardState[i][j] == 1) // 白子
            {
                brush.setColor(Qt::white);
                painter.setBrush(brush);
                painter.drawEllipse(BOARD_EDGE_SPACE + GRID_SIZE * j - STONE_RADIUS,
                                    BOARD_EDGE_SPACE + GRID_SIZE * i - STONE_RADIUS,
                                    STONE_RADIUS * 2, STONE_RADIUS * 2);
            }
            else if (gameEngine->boardState[i][j] == -1) // 黑子
            {
                brush.setColor(Qt::black);
                painter.setBrush(brush);
                painter.drawEllipse(BOARD_EDGE_SPACE + GRID_SIZE * j - STONE_RADIUS,
                                    BOARD_EDGE_SPACE + GRID_SIZE * i - STONE_RADIUS,
                                    STONE_RADIUS * 2, STONE_RADIUS * 2);
            }
        }
    }

    // 修改胜利检查逻辑
    if (hoverRow > 0 && hoverRow < BOARD_DIMENSION &&
        hoverCol > 0 && hoverCol < BOARD_DIMENSION &&
        (gameEngine->boardState[hoverRow][hoverCol] == 1 ||
         gameEngine->boardState[hoverRow][hoverCol] == -1))
    {
        if (gameEngine->checkVictory(hoverRow, hoverCol) &&
            gameEngine->currentState == GAME_ACTIVE)
        {
            gameEngine->currentState = GAME_WIN;
            victorySound.play();

            QString str = (gameEngine->boardState[hoverRow][hoverCol] == 1)
                              ? "white player" : "black player";

            // 使用非阻塞方式处理游戏结束
            QTimer::singleShot(0, [this, str]() {
                QMessageBox::information(this, "congratulations", str + " win!");
                // 延迟重置游戏，确保音效播放完成
                QTimer::singleShot(100, [this]() {
                    gameEngine->initializeGame(currentGameMode);
                    gameEngine->currentState = GAME_ACTIVE;
                    update();
                });
            });
        }
    }

    // 修改平局检查逻辑
    if (gameEngine->checkDraw() && gameEngine->currentState == GAME_ACTIVE)
    {
        gameEngine->currentState = GAME_DRAW;
        defeatSound.play();

        // 使用非阻塞方式处理平局
        QTimer::singleShot(0, [this]() {
            QMessageBox::information(this, "oops", "dead game!");
            QTimer::singleShot(100, [this]() {
                gameEngine->initializeGame(currentGameMode);
                gameEngine->currentState = GAME_ACTIVE;
                update();
            });
        });
    }
}

// 鼠标移动事件：处理鼠标悬停效果
void GomokuMainWindow::mouseMoveEvent(QMouseEvent *event)
{
    int x = event->x();
    int y = event->y();

    // 更严格的边界检查
    if (x >= BOARD_EDGE_SPACE + GRID_SIZE / 2 &&
        x <= size().width() - BOARD_EDGE_SPACE - GRID_SIZE / 2 &&
        y >= BOARD_EDGE_SPACE + GRID_SIZE / 2 &&
        y <= size().height() - BOARD_EDGE_SPACE - GRID_SIZE / 2)
    {
        // 计算行列时考虑边界
        int col = qBound(0, (x - BOARD_EDGE_SPACE) / GRID_SIZE, BOARD_DIMENSION - 1);
        int row = qBound(0, (y - BOARD_EDGE_SPACE) / GRID_SIZE, BOARD_DIMENSION - 1);

        // 更新hover位置
        hoverRow = row;
        hoverCol = col;
    }
    else
    {
        hoverRow = -1;
        hoverCol = -1;
    }

    update();
}

// 鼠标释放事件：处理玩家落子
void GomokuMainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    // 如果不是AI回合或不是人机模式
    if (!(currentGameMode == HUMAN_VS_AI && !gameEngine->isPlayerTurn))
    {
        processHumanMove(); // 处理玩家落子

        // 如果是人机模式且轮到AI
        if (gameEngine->currentMode == HUMAN_VS_AI && !gameEngine->isPlayerTurn)
        {
            // 延迟后执行AI落子
            QTimer::singleShot(AI_THINKING_DELAY, this, SLOT(processAIMove()));
        }
    }
}

// 处理玩家落子
void GomokuMainWindow::processHumanMove()
{
    // 检查落子位置是否有效
    if (hoverRow != -1 && hoverCol != -1 &&
        gameEngine->boardState[hoverRow][hoverCol] == 0)
    {
        gameEngine->humanMove(hoverRow, hoverCol); // 执行落子
        placeStoneSound.play(); // 播放落子音效
        update(); // 更新界面
    }
}

// 处理AI落子
void GomokuMainWindow::processAIMove()
{
    gameEngine->aiMove(hoverRow, hoverCol); // 执行AI落子
    placeStoneSound.play(); // 播放落子音效
    update(); // 更新界面
}
